﻿using iTool.PluginCore;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System.IO;
using System.Threading.Tasks;

namespace Silo.CloudService
{
    public class PluginsProxyMiddleware
    {
        private readonly RequestDelegate next;
        private readonly ServerPluginsManager pluginsManager;

        public PluginsProxyMiddleware(RequestDelegate next, ServerPluginsManager pluginsManager)
        {
            this.next = next;
            this.pluginsManager = pluginsManager;
        }

        public async Task Invoke(HttpContext context)
        {
            context.Response.ContentType = "application/json";

            StreamReader streamReader = new StreamReader(context.Request.Body);
            string bodyContext = await streamReader.ReadToEndAsync();

            try
            {
                var request = JsonConvert.DeserializeObject<PluginRequestBodyParameter>(bodyContext);
                dynamic result = await this.pluginsManager.InvokeAsync(request.PluginName, request.ExportMethodName, request.Parameters);

                dynamic resultValue = null;

                if (result != null)
                {
                    if ("System.Threading.Tasks" == result.GetType().Namespace)
                    {
                        resultValue = await result;
                    }
                    else
                    {
                        resultValue = result;
                    }

                    string body = JsonConvert.SerializeObject(resultValue);
                    await context.Response.WriteAsync(body);
                }
                else
                {
                    await context.Response.WriteAsync(string.Empty);
                }
            }
            catch (System.Exception ex)
            {
                // 发生异常
                context.Response.StatusCode = 500;
                await context.Response.WriteAsync(ex.Message);
            }


            //if (0 == 1)
            //{
            //    await next(context);
            //}

        }
    }


}
